//
//  DemoVC1.m
//  JSBasicFramework
//
//  Created by Apple on 2018/8/2.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "DemoVC1.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <NetworkExtension/NetworkExtension.h>



@interface DemoVC1 ()

@property (nonatomic, strong) JSTableViewHelper *tableViewHelper;

@end

@implementation DemoVC1

- (void)viewDidLoad {
    [super viewDidLoad];
    QMUIButton  *get = [QMUIButton new];
    get.js_normalTitle(@"获取WiFi");
    [self.view addSubview:get];
    [get mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(80, 40));
    }];
    [[get rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"%s",__func__);
        NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
        for (id child in ifs) {
            NSLog(@"ifs.child %@", child);
            id data = (__bridge id)CNCopyCurrentNetworkInfo((CFStringRef)child);
            NSLog(@"data: %@", data);
        }
        
        
        
    }];
}
- (NSString*) getWifiSsid {
    if (@available(iOS 13.0, *)) {
        //用户明确拒绝，可以弹窗提示用户到设置中手动打开权限
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
            NSLog(@"User has explicitly denied authorization for this application, or location services are disabled in Settings.");
            //使用下面接口可以打开当前应用的设置页面
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            return nil;
        }
        CLLocationManager* cllocation = [[CLLocationManager alloc] init];
        if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
            //弹框提示用户是否开启位置权限
            [cllocation requestWhenInUseAuthorization];
            usleep(500);
            //递归等待用户选选择
            return [self getWifiSsid];
        }
    }
    NSString *wifiName = nil;
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    if (!wifiInterfaces) {
        return nil;
    }
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            CFRelease(dictRef);
        }
    }
    
    CFRelease(wifiInterfaces);
    return wifiName;
}


@end
